<?php

namespace app\components\response;

use yii\web\UnauthorizedHttpException;

class Response extends \yii\web\Response {

    public function init()
    {
        parent::init();
        $this->on(\yii\web\Response::EVENT_BEFORE_SEND, [$this, 'beforeSend']);
    }

    /**
     * 更改数据输出格式
     * 默认情况下输出Json数据
     * 如果客户端请求时有传递$_GET['callback']参数，输入Jsonp格式
     * @param \yii\base\Event $event
     */
    public function beforeSend($event){

        /* @var $response \yii\web\Response */
        $response = $event->sender;

        if($response->format == self::FORMAT_HTML){
            return;
        }

        //如果为图片则放行
        if(in_array($response->getHeaders()->get("content-type"),['image/png'])){
            return;
        }

        if($response->isSuccessful){
            $code = "000000";
            $status = "SUCCESS";
            $data = $response->data;
            $msg = "";
        }else{

            $exception = \Yii::$app->getErrorHandler()->exception;
            $data = $this->convertExceptionToArray($exception);
            $code = "900001";
            $status = "FAIL";
            //异常信息处理
            $msg = $exception->getMessage();
            //令牌失效和错误返回特定的状态码
            if($exception instanceof UnauthorizedHttpException){
                $response->statusCode = $exception->statusCode;
            }else{
                $response->statusCode = 200;
            }
        }

        $response->data = [
            'code' => $code,
            'status' => $status,
            'data'=> $data,
            'msg'=>$msg
        ];

        //jsonp 格式输出
        if (isset($_GET['callback'])) {
            $response->format = Response::FORMAT_JSONP;
            $response->data = [
                'callback' => $_GET['callback'],
                'data'=>$response->data,
            ];
        }
    }

    /**
     * 将异常转换为array输出
     * @see \yii\web\ErrorHandle
     * @param \Exception $exception
     * @return array|string
     */
    protected function convertExceptionToArray($exception)
    {
        if (YII_DEBUG) {
            $array['type'] = get_class($exception);
                $array['file'] = $exception->getFile();
                $array['line'] = $exception->getLine();
                $array['stack-trace'] = explode("\n", $exception->getTraceAsString());
                if ($exception instanceof \yii\db\Exception) {
                    $array['error-info'] = $exception->errorInfo;
                }

            if (($prev = $exception->getPrevious()) !== null) {
                $array['previous'] = $this->convertExceptionToArray($prev);
            }
            return $array;
        }else{
            return "";
        }
    }
}